<template>
  <div class="app-container">
    <div class="flex flex-items-center flex-justify-between pb-20px">
      <div class="recarge-wrapper">
        <div class="flex flex-items-center">
          <div class="circle">
            <el-icon><Wallet /></el-icon>
          </div>
          <span>{{ $t('points.当前积分') }}<span class="font-size-20px color-#06C36E ml-10px font-500">{{myscore}} {{ $t('points.积分') }}</span></span>
        </div>
        <el-button type="primary" round @click="pointRechargeShow = true">{{ $t('points.充值积分') }}</el-button>
      </div>
      <el-select v-model="searchData.status" :placeholder="$t('common.全部')" w-118px popper-class="select-self-clas"  w-100px>
        <el-option v-for="item in statusList" :key="item.value" :label="item[CL('label')]" :value="item.value" />
      </el-select>
    </div>

    <div class="table-wrapper" v-loading="loading">
      <el-table
        :data="tableData"
        header-cell-class-name="cell-self-clas"
        cell-class-name="cell-class-name"
        :row-class-name="tableRowClassName"
        size="large"
        border
      >

        <el-table-column prop="good" :label="$t('points.状态')"  align="center" >
          <template #default="{ row }">
            <template v-if="row.type==1">
              {{  row.remark }}
            </template>
            <template v-else-if="locale=='ru'&&row.type==2">
              {{  row.remark_ru }}
            </template>
            <template v-else-if="locale=='zh'&&row.type==2">
              {{  row.remark }}
            </template>
             <!-- {{ ['充值','消费'][row.status]+ row.remark }} -->
          </template>
        </el-table-column>
        <el-table-column prop="score"  :label="$t('points.积分情况')" align="center">
          <template #default="{ row }">
            {{ row.status == 0 ? '+' : '-' }} {{ row.score }}
          </template>
        </el-table-column>
        <el-table-column prop="after"  :label="$t('points.积分余额')" align="center"></el-table-column>
        <el-table-column prop="createtime"  :label="$t('points.时间')" align="center"></el-table-column>
      </el-table>
    </div>
    <div class="pager-wrapper mt-10px">
      <el-pagination :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
        :total="paginationData.total" :page-size="paginationData.pageSize" :current-page="paginationData.currentPage"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>




      <!-- 充值积分 -->
    <el-dialog v-model="pointRechargeShow" :title="$t('points.充值积分')" width="750px" border-rd-24px class="dialog-wrapppx" @close="closePay">
      <div class="dialog-wrapper" v-loading="payLoading">
        <div class="point-lists">
          <div :class="['point',index == currentIndex && 'active']" v-for="(item,index) in pointLists" :key="index" @click="changePoint(index)">
            <img src="/static/img/start.png" alt="" class="start">
            <div class="po-desc">
              <div class="jifen">{{item.name}} {{ $t('points.积分') }}</div>
              <div class="price" v-if="locale=='zh'">￥{{ item.value }}</div>
              <div class="price" v-else>{{ item.value_ru }} Рубль</div>
            </div>
          </div>
        </div>
        <!-- 充值积分 -->
        <div class="recharge-interal">
          <span class="ti">{{$t('points.自定义充值积分')}}</span>
          <el-input-number v-model="defaultPointSelf" :min="2000" :max="1000000000" :controls="false" @focus="onfocusPoint"/>
          <span class="green" v-if="locale=='zh'">={{moneySelf}} {{ $t('order.元') }}</span>
          <span class="green" v-else>={{moneySelf_ru}} Рубль</span>
        </div>
        <div class="pays">
          <div :class="['pay',paytype == 'wx' && 'active']" @click="onPayType('wx')">{{$t('points.微信付款码')}}</div>
          <!-- <div :class="['pay',paytype == 'zfb' && 'active']" @click="onPayType('zfb')">{{$t('points.支付宝收款码')}}</div> -->
        </div>
      </div>
      <template #footer>
        <el-button  @click="pointRechargeShow = false" round>
          {{ $t('good.取消') }}
        </el-button>
        <el-button type="primary"  round @click="onPay">
          {{$t('points.确认支付')}}
        </el-button>
      </template>
    </el-dialog>


    <el-dialog v-model="payCodeBolean" :title="paytype == 'wx' ?  $t('points.微信扫码支付')  :  $t('points.支付宝扫码支付')  " width="300px" border-rd-24px class="dialog-wrapppx" @close="closePay">
      <div class="dialog-wrapper mb-0" v-loading="payLoading">
        <el-image :src="payUrl"></el-image>
      </div>
    </el-dialog>

  </div>
</template>


<script lang="ts" setup>
import type { PointData,PointPayRequest } from "@@/apis/point/type"
import {  getScoreList,PointPay,payCallback } from "@@/apis/point"
import { usePagination } from "@@/composables/usePagination"
import { inject } from 'vue'
const CL: any = inject("$CL");
import { useI18n } from 'vue-i18n';
const { locale, t } = useI18n();//登录国籍
defineOptions({
  // 命名当前组件
  name: "PointRecharge"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const myscore = ref('');

// #region 查
const tableData = ref<PointData[]>([])
const statusList = ref([{
  label: '全部',
  label_ru: 'Все',
  value: -1,
}, {
  label: '充值记录',
  label_ru: 'Пополнения',
  value: 0,
}, {
  label: '消费记录',
  label_ru: 'Расходы',
  value: 1,
}])

const searchData = reactive({
  status: -1,
})



watch(()=>searchData.status,(val)=> {
  getTableData();
})


function getTableData() {
  loading.value = true

  getScoreList({
    page: paginationData.currentPage,
    limit: paginationData.pageSize,
    status: searchData.status,
  }).then(({ data }) => {
    paginationData.total = data.count
    tableData.value = data.list;
    myscore.value = data.myscore; // 总积分
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    loading.value = false
  })
}

// #endregion

// #region 积分充值
type TimeoutId = number | NodeJS.Timeout;

const pointRechargeShow = ref(false);
const currentIndex = ref<null | number>(0);
let payLoading = ref(false)
let paytype = ref('wx')
let payCodeBolean = ref(false)
let payUrl = ref('');
let ordernum = ref('')
let timer:TimeoutId = 0;

const pointLists = ref([{
  name: 2000,
  value: 200,
  value_ru: 3669,
},{
  name: 3000,
  value: 300,
  value_ru: 6115,
},{
  name: 10000,
  value: 900,
  value_ru: 12230,
}])


const changePoint = (index: number)=> {
  currentIndex.value = index;
}

const defaultPointSelf = ref(2000)


const moneySelf = computed(()=> (defaultPointSelf.value / 10).toFixed(1))
const moneySelf_ru = computed(()=> ((defaultPointSelf.value / 10)*12.23).toFixed(1))

const onfocusPoint = ()=> {
  currentIndex.value = null;
}

const onPayType = (py:string)=> {
  paytype.value = py;
}
// 支付
const onPay = ()=> {
  clearTimeout(timer)
  let money = 0,
  points=0;
  if (currentIndex.value === null) { // 自定义积分
    money = +moneySelf.value;
    points = defaultPointSelf.value;
  } else {
    money = pointLists.value[currentIndex.value].value;
    points = pointLists.value[currentIndex.value].name;
  }
  if (points < 500) {
    ElMessage.warning(t('common.积分充值数量最小500'))
    return;
  }
  payLoading.value = true;

  let data:PointPayRequest = {
    paytype: paytype.value,
    service_type: 'points',
    money, // 支付金额
    points, // 充值积分
  }

  PointPay(data).then((res:any) => {
    ordernum.value = res.data?.ordernum;

    if (paytype.value == 'zfb') {
      createAlipay(res.data?.parameter?.data);
    } else {
      payCodeBolean.value = true;
      payUrl.value = res.data?.parameter?.data?.wx_url;
    }
    payLoading.value = false;
    payCallBackFun();
  }).finally(() => {
    payLoading.value = false
  })
}

// 创建阿里支付
const createAlipay = (tml:string)=> {
  let divDom = document.createElement('div');
  divDom.style.display = 'none';
  divDom.innerHTML = tml;
  document.body.appendChild(divDom);

  let form = document.getElementById('alipaysubmit') as HTMLFormElement
  console.log(form,'formformformformformform')
  form.submit();
}

// 支付回调
const payCallBackFun = async ()=> {
  try {
    let res = await payCallback({
      ordernum: ordernum.value,
    })
    if (res.data.status == 1) {
      payCodeBolean.value = false;
      pointRechargeShow.value = false;
      getTableData();
      ElMessage.success('充值成功')
      return;
    }
    timer = setTimeout(() => {
      payCallBackFun();
    }, 2000);
  } catch (error) {
   ElMessage.error(t('common.付款失败') )
    payCodeBolean.value = false;
  }

}


const closePay = ()=> {
  clearTimeout(timer);
}

// #endregion




// 表格隔行变色
interface User {
  date: string
  name: string
  address: string
}
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User
  rowIndex: number
}) => {
  if (rowIndex % 2 == 0) {
    return 'primary-row-color'
  } else {
    return 'info-row-color'
  }
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>


<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.app-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .recarge-wrapper {
    width: 378px;
    height: 56px;
    border-radius: 28px;
    background: rgba(0, 122, 255, 0.10);
    display: flex;
    align-items: center;
    padding: 0 12px;
    justify-content: space-between;
    .circle {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background: #fff;
      margin-right: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      .el-icon {
        color: #007AFF;
        font-size: 18px;
      }
    }
    span {
      color: #1D2129;
      font-size: 20px;
      font-weight: 400;
    }
  }
  .el-select {
    :deep(.el-select__wrapper) {
      border-radius: 16px;
      background: #007AFF;

      .el-select__placeholder {
        color: #fff;
      }

      .el-select__suffix {
        .el-icon {
          color: #fff;
        }
      }
    }
  }



  .table-wrapper {
    flex: 1;
    overflow: hidden;

    .el-table {
      height: 100%;
      border-top-left-radius: 30px;
      border-top-right-radius: 30px;

      :deep(.cell-self-clas) {
        color: #1D2129 !important;
        font-size: 14px;
        font-weight: 400;
        background: #F2F3F5;
        border-right: none;
      }

      :deep(.cell-class-name) {
        color: #1D2129 !important;
        font-size: 14px;
        font-weight: 400;
        padding: 16px;

      }



    }


    .info-self-btn {
      background: #F2F3F5;
      box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
      color: #1D2129;
      border-color: transparent;
    }

    // 标签
    .tag-status {
      height: 32px;
      padding: 0 8px;
      color: #007AFF;
      font-size: 14px;
      font-weight: 400;
      border-radius: 2px;
      background: rgba(0, 122, 255, 0.10);
      line-height: 32px;
      display: inline-block;

      &.active {
        color: #FF010B;
        background: rgba(255, 1, 11, 0.10);
      }
    }


  }


}


// 充值积分
.dialog-wrapppx {
  .dialog-wrapper {
    margin-bottom: 40px;
    .point-lists {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      .point {
        width: 204px;
        height: 86px;
        border-radius: 12px;
        border: 1px solid #E5E6EB;
        background: #FFF;
        display: flex;
        align-items: center;
        padding-left: 16px;
        position: relative;
        margin-right: 16px;
        cursor: pointer;
        user-select: none; /* 对大多数浏览器有效 */
        .start {
          width: 28px;
          height: 28px;
          margin-right: 8px;
        }
        .po-desc {
          .jifen {
            color: #1D2129;
            font-size: 20px;
            font-weight: 500;
            margin-bottom: 2px;
          }
          .price {
            color: #4E5969;
            font-size: 16px;
            font-weight: 500;
          }
        }
        &:hover,&.active {
          border-color: #007AFF;
          background: rgba(0, 122, 255, 0.10);
          transition: all ease .4s;
          .po-desc {
            .jifen {
              color: #007AFF;
            }
            .price {
              color: #007AFF;
            }
          }
        }
      }
    }
    .recharge-interal {
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      .ti {
        color: #1D2129;
        font-size: 16px;
        font-weight: 500;
        margin-right: 16px;
      }
      .el-input-number {
        width: 220px;
        text-align: left;
        :deep(.el-input__wrapper) {
          input {
            text-align: left;
            font-weight: 700;
          }
        }
      }
      .green {
        color: #06C36E;
        font-size: 16px;
        font-weight: 500;
        margin-left: 16px;
      }
    }
    .pays {
      display: flex;
      align-items: center;
      .pay {
        width: 123px;
        height: 123px;
        border-radius: 12px;
        border: 0.5px solid #E5E6EB;
        background: #F2F3F5;
        margin-right: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #1D2129;
        font-size: 16px;
        font-style: normal;
        font-weight: 400;
        cursor: pointer;
        &:hover,&.active {
          border-color: #007AFF;
          background: rgba(0, 122, 255, 0.10);
          transition: all ease .4s;
          color: #007AFF;
        }

      }
    }
  }
}
:deep(.dialog-wrapppx) {
  background: linear-gradient(to right,#FBFCFD,#F5F9FD,#ECF6FD);
}



</style>

